# F:\BaiduNetdiskDownload\3.99\HBuilderX
import os,time
import subprocess
from ftplib import FTP
from typing import List

ignorePath=['']

class CIHelp():
    def __init__(self,host,ftpUser,ftpPwd,ignorePath:List[str]=None):
        self.host = host
        self.ftpUser = ftpUser
        self.ftpPwd = ftpPwd
        self.client = None
        self.ignoreUpFile = ignorePath

    def changePwd(self, ftp, folder,parentRemotePath=''):
        try:
            print(f'更改远程目录到：{folder}')
            ftp.cwd(folder)
        except Exception:
            # 如果远程目录不存在，则创建它
            print(f'create remote path {folder}')
            if parentRemotePath:
                ftp.cwd(parentRemotePath)
            ftp.mkd(folder)
            ftp.cwd(folder)
    def ignore(self,path):
        for ignoreFile in self.ignoreUpFile:
            if ignoreFile in path:
                return True
        return False
    def upload_files(self, ftp, local_dir, remote_dir,parentRemotePath='/'):
        if not remote_dir.startswith('/'):
            remote_dir = '/' + remote_dir
        # if '/static/img' in parentRemotePath:
        #     return
        # 切换回原始远程目录
        
        self.changePwd(ftp,remote_dir,parentRemotePath)
        currentPath = remote_dir
        # 获取本地目录下的所有文件和子目录
        for item in os.listdir(local_dir):
            if currentPath != remote_dir:
                self.changePwd(ftp,remote_dir,parentRemotePath)
                currentPath = remote_dir
            local_path = os.path.join(local_dir, item)
            if self.ignore(local_path):
                continue
            if os.path.isfile(local_path):
                # 上传文件
                print(f"Uploading file: {local_path}")
                times=0
                while True:
                    times+=1
                    try:
                        with open(local_path, 'rb') as file:
                            ftp.storbinary(f'STOR {item}', file)
                        break
                    except Exception as e:
                        print(e)
                        if times>3:
                            print(f'upload {local_path} error,times:{times}')
                            break
            elif os.path.isdir(local_path):
                # 递归处理子目录
                print(f"Processing directory: {local_path}")
                new_remote_dir = f'{remote_dir}/{item}'
                self.upload_files(ftp, local_path, new_remote_dir,remote_dir)
                currentPath=''
    def loginFtp(self):
        # FTP服务器信息
        server = self.host
        username = self.ftpUser
        password = self.ftpPwd
        # remote_directory = "test"

        # 本地目录
        # local_directory = r"C:\workspace\project\mpos\unpackage\dist\build\h5"

        # 连接到FTP服务器
        ftp = FTP()
        ftp.connect(server)
        ftp.set_pasv(False)
        # self.ExcuteSSHCmd('rm -rf /www/wwwroot/mpos.runhis.com/static/js')
        ftp.login(username, password)
        # self.delete_directory(ftp,'/static/js')
        return ftp
    def uploadFile(self,filePath,remote_folder=''):
        print(f'begin upload {filePath}')
        ftp = self.loginFtp()
        try:
            if remote_folder:
                self.changePwd(ftp,remote_folder)
            fileName = filePath.split("/")[-1]
            with open(filePath, 'rb') as file:
                ftp.storbinary(f'STOR {fileName}', file)
            print(f'upload {filePath} success')
        except Exception as e:
            raise e
        finally:
            ftp.quit()
    def uploadToFTP(self,remote_directory, local_directory):
        ftp = self.loginFtp()
        # self.delete_directory(ftp,'/static/js')
        
        try:
            self.upload_files(ftp, local_directory, remote_directory)
        except Exception as e:
            print(e)
        finally:
            ftp.quit()
    def run_command(self, command):
        try:
            process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

            # 实时读取标准输出
            for line in process.stdout:
                print(line, end='')

            # 实时读取标准错误
            for line in process.stderr:
                print(line, end='')

            # 等待子进程结束
            process.wait()

            # 获取返回码
            return_code = process.returncode
            print(f"Command exited with return code {return_code}")
        except subprocess.CalledProcessError as e:
            print("Subprocess error:", e)
        except KeyboardInterrupt:
            print("Interrupted by user")
                
if __name__ == '__main__':
    # mvn clean install
    key = '/data/source/mytool/open/mxtf/guan_key.pem'
    ci = CIHelp('119.91.232.205','javaapp','8XDr3KDYxTEPA3YT',['__pycache__'])
    ci.run_command(['ssh','root@119.91.232.205','-p22','-i',key,"supervisorctl stop pre-cacultor"])
    ci.uploadToFTP('/pre-caulator/src','./src')
    ci.uploadFile('main.py','/pre-caulator')
    ci.run_command(['ssh','root@119.91.232.205','-p22','-i',key,"supervisorctl start pre-cacultor"])
    # time.sleep(5)
    # ci.run_command(['ssh','root@119.91.232.205','-p22','-i',key,"curl http://127.0.0.1:7878/open/start_worker"])
